using System;
using System.Net;
using System.Windows.Forms;
using ProxyServer.Pool;
using ProxyServer.ProxyImpl;
using HttpListener = ProxyServer.ProxyImpl.HttpListener;

namespace ProxyServer.Shell
{
    public partial class MainForm : Form
    {
        private Listener listener;

        public MainForm()
        {
            InitializeComponent();
        }

        private void MainForm_OnLoad(object sender, EventArgs e)
        {
            BufferContext.Init();

            var logger = Logger.GetLogger();
            logger.Logged += Logger_OnLogged;

            BindSetting();
        }

        private void BindSetting()
        {
            var proxyConfig = ProxyConfigManager.ReadSetting();
            hostTextBox.Text = proxyConfig.Host;
            portTextBox.Text = proxyConfig.Port.ToString();
            proxyHostTextBox.Text = proxyConfig.ProxyHost;
            proxyPortTextBox.Text = proxyConfig.ProxyPort.ToString();
            proxyUserTextBox.Text = proxyConfig.ProxyUser;
            proxyPassTextBox.Text = proxyConfig.ProxyPass;
        }

        private void UpdateSetting()
        {
            var proxyConfig = ProxyConfigManager.ReadSetting();
            proxyConfig.Host = hostTextBox.Text;
            proxyConfig.Port = int.Parse(portTextBox.Text);
            proxyConfig.ProxyHost = proxyHostTextBox.Text;
            proxyConfig.ProxyPort = int.Parse(proxyPortTextBox.Text);
            proxyConfig.ProxyUser = proxyUserTextBox.Text;
            proxyConfig.ProxyPass = proxyPassTextBox.Text;
            ProxyConfigManager.SaveSettings(proxyConfig);
        }

        private void Logger_OnLogged(Log log)
        {
            if (InvokeRequired)
            {
                Invoke(new LogPresent(Logger_OnLogged), log);
                return;
            }
            LogTextBox.Text += string.Format("{0} : {1}\r\n", log.Level, log.Message);
        }

        private void ClearToolStripMenuItem_OnClick(object sender, EventArgs e)
        {
            LogTextBox.Text = string.Empty;
        }

        private void LoninButton_OnClick(object sender, EventArgs e)
        {
            if ("Start".Equals(controlButton.Text, StringComparison.CurrentCultureIgnoreCase))
            {
                UpdateSetting();

                listener = new HttpListener();

                listener.Start();

                controlButton.Text = "Stop";
            }
            else if ("Stop".Equals(controlButton.Text, StringComparison.CurrentCultureIgnoreCase))
            {
                listener.Stop();

                controlButton.Text = "Start";
            }
        }
    }
}